package uniandes.dermatologia;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.gson.Gson;

import uniandes.dermatologia.models.Consultation;
import uniandes.dermatologia.resources.Result;
import uniandes.dermatologia.singleton.DermatologiaUniandesApp;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

public class SurveyActivity extends Activity {

	private ListView mainListView;
	private Result[] results;
	private ArrayAdapter<Result> listAdapter;
	private static final String TAG = "SurveyActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_survey);

		mainListView = (ListView) findViewById(R.id.listSurvey);

		mainListView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					@Override
					public void onItemClick(AdapterView<?> parent, View item,
							int position, long id) {
						Result result = listAdapter.getItem(position);
						result.toggleChecked();
						ViewHolder viewHolder = (ViewHolder) item.getTag();
						viewHolder.getCheckBox().setChecked(result.isUtility());
					}
				});

		if (results == null) {
			results = ((DermatologiaUniandesApp) getApplication())
					.getResultsArray();
		}

		ArrayList<Result> resultList = new ArrayList<Result>();
		resultList.addAll(Arrays.asList(results));

		listAdapter = new SurveyArrayAdapter(this, resultList);
		mainListView.setAdapter(listAdapter);

		Button btnFinish = (Button) findViewById(R.id.btnEnviar);

		Typeface font = Typeface.createFromAsset(getAssets(),
				"fonts/Roboto-Light.ttf");

		btnFinish.setTypeface(font);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getMenuInflater().inflate(R.menu.survey, menu);
		return true;
	}

	private static class ViewHolder {
		private CheckBox checkBox;
		private TextView textView;

		public ViewHolder(TextView textView, CheckBox checkBox) {
			this.checkBox = checkBox;
			this.textView = textView;
		}

		public CheckBox getCheckBox() {
			return checkBox;
		}

		public TextView getTextView() {
			return textView;
		}
	}

	private static class SurveyArrayAdapter extends ArrayAdapter<Result> {

		private LayoutInflater inflater;

		public SurveyArrayAdapter(Context context, List<Result> planetList) {
			super(context, R.layout.row_survey, R.id.row_survey_disease,
					planetList);

			inflater = LayoutInflater.from(context);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			Result result = (Result) this.getItem(position);

			CheckBox checkBox;
			TextView textView;

			if (convertView == null) {
				convertView = inflater.inflate(R.layout.row_survey, null);

				textView = (TextView) convertView
						.findViewById(R.id.row_survey_disease);
				checkBox = (CheckBox) convertView.findViewById(R.id.cbSurvey);

				convertView.setTag(new ViewHolder(textView, checkBox));

				checkBox.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						CheckBox cb = (CheckBox) v;
						Result result = (Result) cb.getTag();
						result.setUtility(cb.isChecked());
					}
				});
			}

			else {
				ViewHolder viewHolder = (ViewHolder) convertView.getTag();
				checkBox = viewHolder.getCheckBox();
				textView = viewHolder.getTextView();
			}

			checkBox.setTag(result);

			checkBox.setChecked(result.isUtility());
			textView.setText(result.getDisease().getDiseaseNameRow());

			return convertView;
		}
	}

	public void onClickNext(View v) {
		// ((DermatologiaUniandesApp) getApplication()).beginConsultation();
		String ids = "";
		for (int i = 0; i < results.length; i++) {
			if (results[i].isUtility()) {
				ids += "," + results[i].getResultId() + " "
						+ results[i].getDisease().getDiseaseNameRow();
			}
		}
		((DermatologiaUniandesApp) getApplication()).getCurrentConsultation()
				.setChosenResults(ids);
		Gson gson = new Gson();
		Log.d(TAG,
				"JSON: "
						+ gson.toJson(((DermatologiaUniandesApp) getApplication())
								.getCurrentConsultation()));
		checkExternalMedia();
		writeToSDFile();

		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
		finish();
	}

	private void checkExternalMedia() {
		boolean mExternalStorageAvailable = false;
		boolean mExternalStorageWriteable = false;
		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
		Log.d(TAG, "\n\nExternal Media: readable=" + mExternalStorageAvailable
				+ " writable=" + mExternalStorageWriteable);
	}

	private void writeToSDFile() {

		File root = android.os.Environment.getExternalStorageDirectory();
		File dir = new File(root.getAbsolutePath() + "/download");

		if (!dir.exists()) {
			dir.mkdirs();
		}

		File file = new File(dir, "consultas.txt");

		String ids = "";
		for (int i = 0; i < results.length; i++) {
			// if (results[i].isUtility()) {
			ids += ", " + results[i].getDisease().getDiseaseNameRow() + " "
					+ results[i].getScore();
			// }
		}

		try {
			Consultation temp = ((DermatologiaUniandesApp) getApplication())
					.getCurrentConsultation();

			BufferedWriter bW;

			bW = new BufferedWriter(new FileWriter(file, true));
			bW.newLine();
			bW.write(temp.getLocalDBId() + ";");
			bW.newLine();
			bW.write(temp.getAnamnesis().getBirthDate().toString() + ";");
			bW.newLine();
			bW.write(temp.getAnamnesis().getGender().toString() + ";");
			bW.newLine();
			bW.write(temp.getAnamnesis().getPhototypes().toString() + ";");
			bW.newLine();
			bW.write(temp.getPhysicalExamination().getLesionType().toString()
					+ ";");
			bW.newLine();
			bW.write(temp.getPhysicalExamination().getShape().toString() + ";");
			bW.newLine();
			bW.write(temp.getPhysicalExamination().getNumber().toString() + ";");
			bW.newLine();
			bW.write(temp.getPhysicalExamination().getDistribution().toString()
					+ ";");
			bW.newLine();
			bW.write(temp.getPhysicalExamination().getBorder().toString() + ";");
			bW.newLine();
			bW.write(temp.getPhysicalExamination().getBodyParts().toString()
					+ ";");
			bW.newLine();
			bW.write(temp.getStartDate().toString() + ";");
			bW.newLine();
			bW.write(temp.getPhysicalExamination().getSymptoms().toString()
					+ ";");
			bW.newLine();
			bW.write(temp.getPhysicalExamination().getPast().toString() + ";");
			bW.newLine();
			bW.write("RESULTS: " + ids);
			bW.newLine();
			bW.write("CHOSEN: " + temp.getChosenResults());
			bW.newLine();
			bW.newLine();

			bW.flush();
			bW.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			Log.i(TAG,
					"File not found. Did you"
							+ " add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.d(TAG, "\n\nFile written to " + file);
	}
}
